//
//  JAScrollView.m
//  AutomobileAccessories
//
//  Created by JA on 2017/3/17.
//  Copyright © 2017年  All rights reserved.
//  微信交流:YuChuan0525
//  简书地址：http://www.jianshu.com/p/036be4a428e9
//

#import "JAScrollView.h"

typedef enum : NSUInteger {
    ScrollViewDirectionRight,           /** 向右滚动*/
    ScrollViewDirectionLeft,            /** 向左滚动*/
}ScrollViewDirection;
@interface JAScrollView() <UIScrollViewDelegate>

@end
@implementation JAScrollView

- (instancetype)initWithFrame:(CGRect)frame
{
   self = [super initWithFrame:frame];
    if (self) {
        adScrollView = [[UIScrollView alloc] initWithFrame:frame];
        adScrollView.showsHorizontalScrollIndicator = NO;
        adScrollView.showsVerticalScrollIndicator = NO;
        adScrollView.pagingEnabled = YES;
        adScrollView.delegate = self;
        [self addSubview:adScrollView];

        [self addSubview:self.imageView];
        [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
        [self addSubview:self.pageControl];
        [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_offset(CGSizeMake(SCREENWIDTH * 0.5, 20));
            make.centerX.mas_equalTo(self);
            make.bottom.mas_equalTo(self.mas_bottom).offset(-10);
        }];
    }
    return self;
}
- (void)handleTap:(UITapGestureRecognizer *)tapG
{
    if (self.block)
    {
        self.block(currentPage);
    }
}
- (void)setImagesArray:(NSArray *)imagesArray
{
    _imagesArray = imagesArray;
}
- (void)initView
{
    if (_imagesArray.count == 0) {
        return;
    }
    self.pageControl.numberOfPages = _imagesArray.count;
    self.pageControl.hidden = (_imagesArray.count <= 1);
    self.pageControl.currentPage = currentPage;
    
    NSMutableArray * tempImageArray = [[NSMutableArray alloc] init];

    if (_imagesArray.count > 1) {
        [tempImageArray addObject:[_imagesArray lastObject]];
        for (id obj in _imagesArray)
        {
            [tempImageArray addObject:obj];
        }
        [tempImageArray addObject:[_imagesArray firstObject]];
    }else{
        [tempImageArray addObject:[_imagesArray firstObject]];
    }
    
    picCount = tempImageArray.count;
    [_imageView removeFromSuperview];
    [adScrollView.subviews enumerateObjectsUsingBlock:^(UIImageView *obj, NSUInteger idx, BOOL *stop) {
        [obj removeFromSuperview];
    }];
    
    for (NSInteger i = 0; i < picCount; i ++)
    {
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(i*self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
        [imageV sd_setImageWithURL:[NSURL URLWithString:tempImageArray[i]]];
        imageV.tag = i + 100;
        [adScrollView addSubview:imageV];
    }
    if (self.imagesArray.count > 1) {
        [adScrollView setContentSize:CGSizeMake(self.frame.size.width * picCount, self.frame.size.height)];
        [adScrollView setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
    }else{
        [adScrollView setContentSize:CGSizeMake(self.frame.size.width * picCount, self.frame.size.height)];
        [adScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    
    if (_imagesArray.count > 1) {
        NSTimeInterval timeInterval = 3.f;
        if (self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.timer = [NSTimer timerWithTimeInterval:timeInterval target:self selector:@selector(moveAd) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
   
    [self.layer setMasksToBounds:YES];
    
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    tapG.numberOfTapsRequired = 1;
    [self addGestureRecognizer:tapG];
}
- (UIImageView *)imageView
{
    if (!_imageView) {
        _imageView = [UIImageView new];
        _imageView.backgroundColor = [UIColor clearColor];
    }
    return _imageView;
}
- (UIPageControl *)pageControl
{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        [_pageControl setValue:[UIImage imageNamed:@"home_unPageControl"] forKeyPath:@"_pageImage"];
        [_pageControl setValue:[UIImage imageNamed:@"home_pageControl"] forKeyPath:@"_currentPageImage"];
    }
    return _pageControl;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat Width = self.frame.size.width;
    if (scrollView.contentOffset.x == self.frame.size.width)
    {
        flag = YES;
    }
    if (flag)
    {
        if (scrollView.contentOffset.x <= 0)
        {
            [adScrollView setContentOffset:CGPointMake(Width*(picCount - 2), 0) animated:NO];
        }else if (scrollView.contentOffset.x >= Width*(picCount - 1))
        {
            [adScrollView setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
        }
        else
        {
            currentPage = scrollView.contentOffset.x/self.frame.size.width - 1;
            [self.pageControl setCurrentPage:currentPage];
            scrollTopicFlag = currentPage+2==2?2:currentPage+2;
        }
    }
}

- (void)moveAd
{
    [adScrollView setContentOffset:CGPointMake(self.frame.size.width*scrollTopicFlag, 0) animated:YES];
    
    if (scrollTopicFlag > picCount)
    {
        scrollTopicFlag = 1;
    }else
    {
        scrollTopicFlag ++;
    }
}

- (void)dealloc
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}
@end
